package com.ruoyi;

import com.ruoyi.business.constant.TradeConstants;
import com.ruoyi.business.publisher.MessagePublisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 启动程序
 *
 * @author ruoyi
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableScheduling
public class RuoYiApplication implements CommandLineRunner {

    @Value("${server.pythonPath}")
    private String pythonPath;

    @Value("${server.startListen}")
    private Boolean startListen;


    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(RuoYiApplication.class);
    public static void main(String[] args) {
        // System.setProperty("spring.devtools.restart.enabled", "false");
        SpringApplication.run(RuoYiApplication.class, args);
        System.out.println("(♥◠‿◠)ﾉﾞ  若依启动成功   ლ(´ڡ`ლ)ﾞ  \n" +
                " .-------.       ____     __        \n" +
                " |  _ _   \\      \\   \\   /  /    \n" +
                " | ( ' )  |       \\  _. /  '       \n" +
                " |(_ o _) /        _( )_ .'         \n" +
                " | (_,_).' __  ___(_ o _)'          \n" +
                " |  |\\ \\  |  ||   |(_,_)'         \n" +
                " |  | \\ `'   /|   `-'  /           \n" +
                " |  |  \\    /  \\      /           \n" +
                " ''-'   `'-'    `-..-'              ");
    }


    @PostConstruct
    private void stockStart() {
        new Thread(this::stockServer).start();
    }

    private void stockServer() {
        try {
            int PORT = 8000;  // 请确保与Python客户端中的端口一致
            try (ServerSocket serverSocket = new ServerSocket(PORT)) {
                System.out.println("Java server listening on port " + PORT);

                while (true) {
                    Socket clientSocket = serverSocket.accept();

                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8))) {

                        String dataFromPython = in.readLine();
                        // 处理接收到的数据...
                        if (startListen) {
                            redisTemplate.opsForList().leftPush(TradeConstants.TICKET_QUEUE, dataFromPython);
                            logger.info("Received data from Python:{} ", dataFromPython);
                            in.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.err.println("Error reading data from Python client: " + e.getMessage());
                    } finally {
                    clientSocket.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run(String... args) {
        executePythonScript();
    }

    private void executePythonScript() {
        try {

            // 指定Python解释器路径和Python脚本路径
            String command = "python " + pythonPath;
            Process process = Runtime.getRuntime().exec(command);

            // 读取Python脚本的输出
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(), "gb2312"));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8));

            // 输出Python脚本的标准输出和标准错误
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            while ((s = stdError.readLine()) != null) {
                System.err.println(s);
            }

            // 等待Python脚本执行完毕并获取退出状态
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : " + exitCode);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
